<template>
    <div>
        <div class="sku_container">
            <div v-for="(attribute,index) in commodityInfo.attr" :key="attribute.id">
                <div class="sku_attr">
                    <span>属性名:</span>
                    <el-input size="mini" class="attr_input" v-model="attribute.name"></el-input>
                </div>
                <div class="sku_attr_props">
                    <span>属性值:</span>
                    <el-popover placement="bottom" trigger="click" width="120" v-for="(attr_val,prop_index) in attribute.values" :key="attr_val.id">
                        <!-- <el-button slot="reference">{{attr_val.value}}</el-button> -->
                        <el-input size="mini" class="" v-model.trim="attr_val.value"></el-input>
                        <div style="pointer-events: auto;"  slot="reference" class="props_item">
                            <span>
                                <i class="el-icon-close" @click="deleteProp(index,prop_index)"></i>
                            </span>
                            <div class="item_val">{{attr_val.value}}</div>
                        </div>
                    </el-popover>
                    <el-input class="attr_prop_input"  size="mini" placeholder="请输入内容" v-model="addValues[index]" >
                        <el-button slot="append" icon="el-icon-plus" @click="addProperty(index)"></el-button>
                    </el-input>
                </div>
            </div>
            <div class="add_attr">
                <el-button @click="addAttr">添加属性</el-button>
            </div>
        </div>
        <div class="sku_container">
            <div class="attr_prop" v-for="(attribute,index) in commodityInfo.attr" :key="attribute.id">
                <div class="attr">
                    {{attribute.name}}:
                    <el-button size="mini" :type="(activePropery[index] && activePropery[index].value == prop.value) ? 'primary' : ''"  v-for="prop in attribute.values" :key="prop.value" @click="selectProp(index, prop)">{{prop.value}}</el-button>
                </div>
            </div>
            <div class="add_sku">
                <el-button @click="addSku">添加属性</el-button>
            </div>
        </div>
        <div class="sku_container">
                <el-button @click="addSkus">添加sku</el-button>
          <el-table :data="skus" style="width: 100%" :span-method="skuSpanMethod">
            <el-table-column v-for="(attribute) in commodityInfo.attr" :label="attribute.name" :prop="attribute.name" :key="attribute.name">
            </el-table-column>
            <el-table-column label="价格" prop="price" >
              <template slot-scope="scope">
                <el-input-number v-model="scope.row.price" size="mini" ></el-input-number>
              </template>
            </el-table-column>
            <el-table-column label="库存" prop="stock" >
              <template slot-scope="scope">
                <el-input-number v-model="scope.row.stock" size="mini" ></el-input-number>
              </template>
            </el-table-column>
          </el-table>
        </div>
    </div>
</template>

<script>
import api from '@/config/server.js'
export default {
  data () {
    return {
      attributes: [
        '颜色', '内存'
      ],
      commodityInfo: {
        attr: [],
        skusMap: {}
      },
      addValues: [],
      activePropery: [],
      newSkus: [],
      skus: []
    }
  },
  created () {
    this.getSkus()
  },
  computed: {

  },
  methods: {
    addProperty (index) {
      let val = this.addValues[index]
      if (!val) {
        return
      }
      if (this.containsProperty(index, val)) {
        this.addValues[index] = ''
        this.addValues.__ob__.dep.notify()
        return
      }
      this.commodityInfo.attr[index].values.push({
        value: val,
        attrName: this.commodityInfo.attr[index].name
      })
      this.addValues[index] = ''
      this.addValues.__ob__.dep.notify()
      this.getSkus()
    },
    // 判断是否存在该property
    containsProperty (index, propertyValue) {
      for (let i = 0; i < this.commodityInfo.attr[index].values.length; i++) {
        if (this.commodityInfo.attr[index].values[i].value === propertyValue) {
          return true
        }
      }
      return false
    },
    deleteProp (index, propIndex) {
      console.log(this.commodityInfo.attr[index].values)
      this.commodityInfo.attr[index].values.splice(propIndex, 1)
    },
    editProp (index, propIndex) {
      if (this.commodityInfo.attr[index].values[propIndex].newValue) {
        this.commodityInfo.attr[index].values[propIndex].value = this.commodityInfo.attr[index].values[propIndex].newValue
      }
    },
    addAttr () {
      this.commodityInfo.attr.push({
        name: '',
        values: []
      })
      this.getSkus()
    },
    selectProp (index, prop) {
      console.log(prop)
      if (this.activePropery[index] && this.activePropery[index].value === prop.value) {
        let tmp = [...this.activePropery]
        tmp[index] = {}
        this.activePropery = tmp
      } else {
        let tmp = [...this.activePropery]
        tmp[index] = prop
        this.activePropery = tmp
      }
    },
    fundPorpertyById (id) {
      for (var j = 0, len = this.commodityInfo.attr.length; j < len; j++) {
        let attr = this.commodityInfo.attr[j]
        for (var k = 0, len2 = attr.values.length; k < len2; k++) {
          let property = attr.values[k]
          if (property.id === id) {
            return {name: attr.name, value: property.value}
          }
        }
      }
    },
    addSku () {
      let tempSku = {
        attibutes: []
      }
      for (var i = 0; i < this.activePropery.length; i++) {
        let property = this.activePropery[i]
        if (property.attrName) {
          tempSku.attibutes.push({
            name: property.attrName,
            value: property.value
          })

          tempSku[property.attrName] = property.value
        } else {
          let attr = this.fundPorpertyById(property.id)
          tempSku.attibutes.push({
            name: attr.name,
            value: property.value
          })
          tempSku[attr.name] = property.value
        }
      }
      this.newSkus.push(tempSku)
      this.getSkus()
    },
    getSkus () {
      let attrProps = []
      for (var i = 0, len = this.commodityInfo.attr.length; i < len; i++) {
        let attr = this.commodityInfo.attr[i]
        let props = []
        for (var j = 0, lenj = attr.values.length; j < lenj; j++) {
          props.push(attr.values[j])
        }
        attrProps.push(props)
      }
      let res = this.calcDescartes(attrProps)
      let sku = res.map(item => {
        let sku = {}
        if (Array.isArray(item)) {
          item.forEach(prop => {
            sku[prop.attrName] = prop.value
            sku.attributes = item.map(attrProp => {
              return {
                attributeName: attrProp.attrName,
                value: attrProp.value
              }
            })
          })
        } else {
          sku.attributes = [{attributeName: item.attrName, value: item.value}]
          sku[item.attrName] = item.value
        }
        sku.price = 0
        sku.stock = 0
        return sku
      })
      this.skus = sku
    },
    calcDescartes (array) {
      if (!array || array.length === 0) { return array }
      return [].reduce.call(array, function (current, set) {
        let res = []
        current.forEach(curentElement => {
          set.forEach(setElement => {
            let t = [].concat(Array.isArray(curentElement) ? curentElement : [curentElement])
            t.push(setElement)
            res.push(t)
          })
        })
        return res
      })
    },
    skuSpanMethod ({ row, column, rowIndex, columnIndex }) {
      if (column.property === 'price' || column.property === 'stock') {
        return [1, 1]
      }
      // let attrNum = this.getSkuAttrNum(row.attributes[columnIndex])
      // console.log(row.attributes[columnIndex].attributeName + ':' + row.attributes[columnIndex].value + '有' + attrNum + '条')
      // if (attrNum === 1) {
      //   console.log('[1, 1]')
      //   return [1, 1]
      // }
      // let firstAttrNum = this.getSkuAttrFirstPosition(row.attributes[columnIndex])
      // console.log(row.attributes[columnIndex].attributeName + ':' + row.attributes[columnIndex].value + '第一条排' + firstAttrNum + '')
      // if (rowIndex === firstAttrNum) {
      //   console.log('[' + attrNum + ', 1]')
      //   return [attrNum, 1]
      // } else {
      //   console.log('[0, 1]')
      //   return [0, 1]
      // }
      return this.getSpan(row.attributes[columnIndex], rowIndex)
    },
    // 判断这一行上一个sku的属性是不是和本行的属性相同，如果相同 这一列不占空间
    getSpan (attrValue, rowIndex) {
      console.log(this.skus, attrValue, rowIndex)
      // 判断这一列前一个sku的属性值是不是和这一行相同
      if (rowIndex === 0) {
        // 第一行
        let num = 1
        for (let i = rowIndex + 1; i < this.skus.length; i++) {
          if (this.skus[i][attrValue.attributeName] === attrValue.value) {
            num++
          } else {
            break
          }
        }
        console.log(num + ',1')
        return [num, 1]
      } else {
        if (this.skus[rowIndex - 1][attrValue.attributeName] === attrValue.value) {
          // 前一行和这一行的属性一样
          console.log('0,1')
          return [0, 1]
        } else {
          let num = 1
          for (let i = rowIndex + 1; i < this.skus.length; i++) {
            if (this.skus[i][attrValue.attributeName] === attrValue.value) {
              num++
            } else {
              break
            }
          }
          console.log(num + ',1')
          return [num, 1]
        }
      }
    },
    addSkus () {
      console.log(this.skus)
      let addData = {
        commodityId: this.$route.params.id,
        sku: this.skus.map(sku => {
          return {
            price: sku.price,
            stock: sku.stock,
            attributes: sku.attributes
          }
        })
      }
      api.addCommoditySku(addData).then((res) => {
        if (res.ret === 1) {
          this.$message('添加成功')
        } else {
          this.$message(res.msg)
        }
      })
      console.log(addData)
    }
  }
}
</script>

<style lang="scss" scope>
    .w-200{
      width:200px;
    }
    .sku_container{
        border: 1px solid #e5e5e5;
        padding: 10px;
        text-align: left;
        .sku_attr{
            position: relative;
            padding: 7px 10px;
            background-color: #f8f8f8;
            line-height: 16px;
            font-weight: 400;
            .attr_input{
                width:200px;
            }
        }
        .sku_attr_props{
            position: relative;
            padding: 7px 10px;
            line-height: 16px;
            font-weight: 400;
            .attr_prop_input{
                width:200px;
            }
            .props_item{
                position:relative;
                background-color: #f8f8f8;
                padding: 10px;
                display: inline-block;
                margin-right: 10px;
                vertical-align: middle;
                text-align: center;
                position: relative;
                border-radius: 2px;
                cursor: pointer;
                &:hover{
                    span{
                        display: block;
                    }
                }
                span{
                    position: absolute;
                    top:-8px;
                    right:-8px;
                    border-radius: 50%;
                    background-color: #999;
                    padding: 2px 2px 2px 2px;
                     display: none;
                    i{
                        color:white;
                    }
                }
                .item_val{
                    display: block;
                    width: 74px;
                    margin: 0 auto;
                    overflow: hidden;
                    text-overflow: ellipsis;
                    white-space: nowrap;
                }
            }
        }
        .add_attr{
        }
        .attr_prop{
            padding: 7px 10px;
        }
    }
</style>
